package com.example.nebulaspringboot.controller;

import com.example.nebulaspringboot.entity.Role;
import com.example.nebulaspringboot.entity.User;
import com.example.nebulaspringboot.error.BusinessException;
import com.example.nebulaspringboot.error.EmBusinessError;
import com.example.nebulaspringboot.service.RoleService;
import com.example.nebulaspringboot.service.UserService;
import com.example.nebulaspringboot.service.model.UserModel;
import com.example.nebulaspringboot.utils.CommonReturnType;
import com.example.nebulaspringboot.utils.JsonResult;
import com.example.nebulaspringboot.utils.NebulaEnums;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @GetMapping("/list")
    public String list(Model model) {
        List<UserModel> userModelList = userService.selectUserList();
        model.addAttribute("users", userModelList);
        return "user/user";
    }

    @GetMapping("/get")
    public UserModel index(@RequestParam(name = "id")Integer id) {
        UserModel userModel = userService.selectByPrimaryKey(id);
        return userModel;
    }

    @GetMapping("/add")
    public String add(Model model) {
        List<Role> roleList = roleService.selectRoleList("");
        model.addAttribute("roleList",roleList);
        return "user/add";
    }

    @PostMapping("/save")
    @ResponseBody
    public CommonReturnType save(@RequestParam(name = "username")String username,
                       @RequestParam(name = "role")Integer role,
                       @RequestParam(name = "telphone")String telphone,
                       @RequestParam(name = "age") Integer age,
                       @RequestParam(name = "email") String email,
                       @RequestParam(name = "realName") String realName) throws UnsupportedEncodingException, NoSuchAlgorithmException, BusinessException {
        User user = new User();
        user.setUsername(username);
        user.setPassword(this.EncoderByMd5("123456"));
        user.setEmail(email);
        user.setRoleId(role);
        user.setRealName(realName);
        user.setTelphone(telphone);
        user.setAge(age);
        userService.insertSelective(user);
        return CommonReturnType.create(null);
    }

    @GetMapping("/edit")
    public String edit(@RequestParam(name = "id")Integer id,Model model) {
        List<Role> roleList = roleService.selectRoleList("");
        UserModel user = userService.selectByPrimaryKey(id);
        model.addAttribute("roleList",roleList);
        model.addAttribute("user",user);
        return "user/edit";
    }

    @PostMapping("/toEdit")
    @ResponseBody
    public CommonReturnType toEdit(@RequestParam(name = "username")String username,
                         @RequestParam(name = "id")Integer id,
                         @RequestParam(name = "role")Integer role,
                         @RequestParam(name = "telphone")String telphone,
                         @RequestParam(name = "age") Integer age,
                         @RequestParam(name = "email") String email,
                         @RequestParam(name = "realName") String realName) throws BusinessException {
        User user = new User();
        user.setId(id);
        user.setUsername(username);
        user.setEmail(email);
        user.setRoleId(role);
        user.setRealName(realName);
        user.setTelphone(telphone);
        user.setAge(age);
        userService.updateByIdSelective(user);
        return CommonReturnType.create(null);
    }

    @GetMapping("/delete")
    @ResponseBody
    public CommonReturnType deleteById(@RequestParam(name = "id")Integer id) throws BusinessException {
        UserModel userModel = userService.selectByPrimaryKey(id);
        if(userModel == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        userService.deleteById(id);
        return CommonReturnType.create(null);
    }

    /**
     * 密码MD5加密
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    private String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        //加密字符串
        String newstr = base64Encoder.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }
}
